using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Data.SqlClient;

using System.Data;
using System.Data.Common;

using Pampa.Common.Utils;

using Pampa.Grid.Core;
using Pampa.Grid.Core.Filters;

namespace Pampa.Grid.Data
{
    public class SqlCommandBuilder : AbstractQueryBuilder
    {
        #region Public Functions

        public virtual IDbCommand GetSelectCommand()
        {
            return GetSelectCommand(null);
        }

        /// <summary>
        /// Devuelve el command (Select) que representa el objeto
        /// </summary>
        /// <returns></returns>
        public virtual IDbCommand GetSelectCommand(int? top)
        {
            IDbCommand command = CreateCommand();

            command.CommandText = GetQueryString(top);

            foreach (KeyValuePair<string, object> parameter in parameters)
            {
                command.Parameters.Add(CreateParameter(parameter.Key, parameter.Value));
            }

            return command;
        }

        /// <summary>
        /// Devuelve un command que permite consultar la cantidad de filas que resultarian de ejecutar el command original
        /// </summary>
        /// <returns></returns>
        public virtual IDbCommand GetCountCommand()
        {
            IDbCommand command = CreateCommand();

            command.CommandText = GetCountQueryString();

            foreach (KeyValuePair<string, object> parameter in parameters)
            {
                command.Parameters.Add(CreateParameter(parameter.Key, parameter.Value));
            }

            return command;
        }

        #endregion

        #region Propietary Functions

        /// <summary>
        /// cambiando solamente estas funciones se podria implementar un SqlOracleCommandBuilder
        /// </summary>
        protected override string GetParameterWithMark(string paramName)
        {
            return "@" + paramName;
        }

        protected virtual IDbCommand CreateCommand()
        {
            return new SqlCommand();
        }

        protected virtual DbParameter CreateParameter(string paramName, object value)
        {
            return new SqlParameter(paramName, value);
        }

        protected override string GetSelectClause(int? top)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(top.HasValue ? " TOP " + top.Value.ToString() : "");
            sb.AppendLine(" " + GetAlias(Source) + ".* ");

            return sb.ToString();
        }

        #endregion
    }
}
